package com.macbulldev.poc.testgin.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.macbulldev.poc.testgin.domain.AppUser;
import com.macbulldev.poc.testgin.domain.EventLog;
import com.macbulldev.poc.testgin.domain.PolicyForm;
import com.macbulldev.poc.testgin.domain.StateOrProvince;
import com.macbulldev.poc.testgin.domain.TransactionQuestion;
import com.macbulldev.poc.testgin.domain.TrialGroup;
import com.macbulldev.poc.testgin.domain.Underwriter;
import com.macbulldev.poc.testgin.service.WebappUtils;


@org.springframework.roo.addon.web.mvc.controller.RooWebScaffold(path = "transactionquestion", automaticallyMaintainView = true, formBackingObject = com.macbulldev.poc.testgin.domain.TransactionQuestion.class)
@org.springframework.web.bind.annotation.RequestMapping("/transactionquestion/**")
@org.springframework.stereotype.Controller
public class TransactionQuestionController {
	
	private static final Logger LOGGER = Logger.getLogger(TransactionQuestion.class);

	
	@RequestMapping(value = "/transactionquestion/ajax/addToGroup", method = RequestMethod.POST)    
	public String addToGroup(@RequestParam(value="groupId", required=false) Long groupId,
    		@RequestParam(value="questions", required=false) String questions,
    		ModelMap modelMap){ 
		
		
		//Add Transaction Questions
		TrialGroup tg = TrialGroup.findTrialGroup(groupId);
		String[] tqArr = questions.split(",");
		
		for(String tq : tqArr)
		{
			if(tq.trim().length() > 0)
			{
				String q = tq.split(":")[0];
				String a = tq.split(":")[1];
				
				
				
				TransactionQuestion newTq = new TransactionQuestion();
				newTq.setQuestion(q);
				newTq.setAnswer(a);
				newTq.setTrialGroup(tg);
				newTq.setType("transaction");
				newTq.persist();
			
			}
		}
		
			modelMap.addAttribute("msg","success");
			return "scenario/ajax_success";
    }
	
	@RequestMapping(value = "/transactionquestion", method = RequestMethod.POST)    
    public String create(@Valid TransactionQuestion transactionQuestion, BindingResult result, ModelMap modelMap) {    
        if (transactionQuestion == null) throw new IllegalArgumentException("A transactionQuestion is required");        
        if (result.hasErrors()) {        
            modelMap.addAttribute("transactionQuestion", transactionQuestion);            
            modelMap.addAttribute("stateorprovinces", StateOrProvince.findAllStateOrProvinces());            
            modelMap.addAttribute("trialgroups", TrialGroup.findAllTrialGroups());            
            modelMap.addAttribute("transactionQuestion_CreateTs_date_format", org.joda.time.format.DateTimeFormat.patternForStyle("S-", org.springframework.context.i18n.LocaleContextHolder.getLocale()));            
            modelMap.addAttribute("transactionQuestion_UpdateTs_date_format", org.joda.time.format.DateTimeFormat.patternForStyle("S-", org.springframework.context.i18n.LocaleContextHolder.getLocale()));            
            return "transactionquestion/create";            
        }        
        transactionQuestion.persist();        
        return "redirect:/transactionquestion/" + transactionQuestion.getId();        
    }
	
	@RequestMapping(value = "/transactionquestion/filter", method = RequestMethod.GET)    
    public String renderPolicyFormFilteredList(@RequestParam(value = "pageNumber", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size,@RequestParam(value = "stateOrProvince", required = false) Long stateOrProvinceId,ModelMap modelMap) {    
		
		int sizeNo = 100;
        int pageNumber= page == null ? 0 : page;
        String url = "transactionquestion/list";
        
        if(stateOrProvinceId == 0)
        {
        	/*
        	sizeNo = 20;
        	modelMap.addAttribute("stateorprovince",stateOrProvinceId);
        	modelMap.addAttribute("stateorprovinces",StateOrProvince.findAllStateOrProvinces());
        	modelMap.addAttribute("transactionquestions", TransactionQuestion.findTransactionQuestionsForStates(pageNumber * sizeNo, sizeNo));            
            Long count = TransactionQuestion.countTransactionQuestionsForStates();
            modelMap.addAttribute("maxPageNumber", (Long)(count/sizeNo));
            */
        	return "redirect:/transactionquestion/list";   
        }
        else
        {
        	modelMap.addAttribute("stateorprovince",stateOrProvinceId);
        	modelMap.addAttribute("stateorprovinces",StateOrProvince.findAllStateOrProvinces());
        	List<TransactionQuestion> transactionquestions = null;
        	transactionquestions = StateOrProvince.findStateOrProvince(stateOrProvinceId).getTransactionQuestions();
            modelMap.addAttribute("transactionquestions",transactionquestions);
            Long count = Long.valueOf(transactionquestions.size());
            modelMap.addAttribute("maxPageNumber", (Long)(count/sizeNo));
        }
        
        return url;        
    }

	@RequestMapping(value = "/transactionquestion/form", method = RequestMethod.GET)    
    public String createForm(ModelMap modelMap) {    
        modelMap.addAttribute("transactionQuestion", new TransactionQuestion());        
        modelMap.addAttribute("stateorprovinces", StateOrProvince.findAllStateOrProvinces());        
        modelMap.addAttribute("trialgroups", TrialGroup.findAllTrialGroups());        
        modelMap.addAttribute("transactionQuestion_CreateTs_date_format", org.joda.time.format.DateTimeFormat.patternForStyle("S-", org.springframework.context.i18n.LocaleContextHolder.getLocale()));        
        modelMap.addAttribute("transactionQuestion_UpdateTs_date_format", org.joda.time.format.DateTimeFormat.patternForStyle("S-", org.springframework.context.i18n.LocaleContextHolder.getLocale()));        
        return "transactionquestion/create";        
    }

	@RequestMapping(value = "/transactionquestion/{id}", method = RequestMethod.GET)    
    public String show(@PathVariable("id") Long id, ModelMap modelMap) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        modelMap.addAttribute("transactionQuestion_CreateTs_date_format", org.joda.time.format.DateTimeFormat.patternForStyle("S-", org.springframework.context.i18n.LocaleContextHolder.getLocale()));        
        modelMap.addAttribute("transactionQuestion_UpdateTs_date_format", org.joda.time.format.DateTimeFormat.patternForStyle("S-", org.springframework.context.i18n.LocaleContextHolder.getLocale()));        
        modelMap.addAttribute("transactionQuestion", TransactionQuestion.findTransactionQuestion(id));        
        return "transactionquestion/show";        
    }

	@RequestMapping(value = "/transactionquestion/list", method = RequestMethod.GET)    
    public String list(@RequestParam(value = "pageNumber", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, ModelMap modelMap) {    
		
		
		int sizeNo = 20;           
        int pageNumber= page == null ? 0 : page;
        
        modelMap.addAttribute("transactionquestions", TransactionQuestion.findTransactionQuestionsForStates(pageNumber * sizeNo, sizeNo));            
        
        Long count = TransactionQuestion.countTransactionQuestionsForStates();
        modelMap.addAttribute("maxPageNumber", (Long)(count/sizeNo));
        
        LOGGER.debug("Page Number:  "+pageNumber);
        LOGGER.debug("Transaction Question List Size:  "+TransactionQuestion.findTransactionQuestionsForStates(pageNumber * sizeNo, sizeNo).size());
        LOGGER.debug("Transaction Question Count:  "+count);
        
        modelMap.addAttribute("transactionQuestion_CreateTs_date_format", org.joda.time.format.DateTimeFormat.patternForStyle("S-", org.springframework.context.i18n.LocaleContextHolder.getLocale()));        
        modelMap.addAttribute("transactionQuestion_UpdateTs_date_format", org.joda.time.format.DateTimeFormat.patternForStyle("S-", org.springframework.context.i18n.LocaleContextHolder.getLocale()));        
        modelMap.addAttribute("stateorprovinces",StateOrProvince.findAllStateOrProvinces());
        
        return "transactionquestion/list";        
    }
	
	@Transactional
	@RequestMapping(method = RequestMethod.PUT)    
    public String update(@Valid TransactionQuestion transactionQuestion, BindingResult result, ModelMap modelMap,HttpSession session) {    
        if (transactionQuestion == null) throw new IllegalArgumentException("A transactionQuestion is required");        
        if (result.hasErrors()) {        
            modelMap.addAttribute("transactionQuestion", transactionQuestion);            
            modelMap.addAttribute("stateorprovinces", StateOrProvince.findAllStateOrProvinces());            
            modelMap.addAttribute("trialgroups", TrialGroup.findAllTrialGroups());            
            modelMap.addAttribute("transactionQuestion_CreateTs_date_format", org.joda.time.format.DateTimeFormat.patternForStyle("S-", org.springframework.context.i18n.LocaleContextHolder.getLocale()));            
            modelMap.addAttribute("transactionQuestion_UpdateTs_date_format", org.joda.time.format.DateTimeFormat.patternForStyle("S-", org.springframework.context.i18n.LocaleContextHolder.getLocale()));            
            return "transactionquestion/update";            
        }
        
		
		AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
		transactionQuestion.setUpdateUsername(sessionUser.getName());
		transactionQuestion.setUpdateTs(new Date());
		

		EventLog log = new EventLog();
    	log.setCreateTs(new Date());
    	log.setCreateUsername(sessionUser.getName());

    	log.setObjectClass(TransactionQuestion.class.getSimpleName());
    	log.setOperation(StateOrProvince.findStateOrProvince(transactionQuestion.getStateOrProvince().getId()).getCode()+" - "+transactionQuestion.getQuestion()+" Updated");
    	log.persist();
        
    	List<TrialGroup> trialGroupList = TrialGroup.findTrialGroupsByStateOrProvince(TransactionQuestion.findTransactionQuestion(transactionQuestion.getId()).getStateOrProvince());
        
    	
    	for(TrialGroup tg : trialGroupList)
        {
        	Set<TransactionQuestion> transactionquestions = tg.getTransactionQuestions();

        	for(TransactionQuestion tQuestion : transactionquestions)
        	{

        		if(tQuestion.getQuestion().equalsIgnoreCase(TransactionQuestion.findTransactionQuestion(transactionQuestion.getId()).getQuestion()))
        		{
        			tQuestion.setQuestion(transactionQuestion.getQuestion());
        			tQuestion.merge();
        		}
        	}
        }
        
        
        
        transactionQuestion.merge();
        
        return "redirect:/transactionquestion/" + transactionQuestion.getId();        
    }

	@RequestMapping(value = "/transactionquestion/{id}/form", method = RequestMethod.GET)    
    public String updateForm(@PathVariable("id") Long id, ModelMap modelMap) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        modelMap.addAttribute("transactionQuestion", TransactionQuestion.findTransactionQuestion(id));        
        modelMap.addAttribute("stateorprovinces", StateOrProvince.findAllStateOrProvinces());        
        modelMap.addAttribute("trialgroups", TrialGroup.findAllTrialGroups());        
        modelMap.addAttribute("transactionQuestion_CreateTs_date_format", org.joda.time.format.DateTimeFormat.patternForStyle("S-", org.springframework.context.i18n.LocaleContextHolder.getLocale()));        
        modelMap.addAttribute("transactionQuestion_UpdateTs_date_format", org.joda.time.format.DateTimeFormat.patternForStyle("S-", org.springframework.context.i18n.LocaleContextHolder.getLocale()));        
        return "transactionquestion/update";        
    }
	
	@Transactional
	@RequestMapping(value = "/transactionquestion/{id}", method = RequestMethod.DELETE)    
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size,HttpSession session) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
              
        
        
        List<TrialGroup> trialGroupList = TrialGroup.findTrialGroupsByStateOrProvince(TransactionQuestion.findTransactionQuestion(id).getStateOrProvince());
        List<TransactionQuestion> deleteList = new ArrayList<TransactionQuestion>();
        
        
        LOGGER.error("Trial Groups By State Size:  "+trialGroupList.size());
        
        for(TrialGroup tg : trialGroupList)
        {
        	Set<TransactionQuestion> transactionquestions = tg.getTransactionQuestions();
        	
        	LOGGER.error("Transaction Questions in Trial Group:  "+transactionquestions.size());
        	
        	
        	for(TransactionQuestion tQuestion : transactionquestions)
        	{
        		
        		LOGGER.error(tQuestion.getQuestion()+"  vs   "+TransactionQuestion.findTransactionQuestion(id).getQuestion());
        		
        		if(tQuestion.getQuestion().equalsIgnoreCase(TransactionQuestion.findTransactionQuestion(id).getQuestion()))
        		{
        			deleteList.add(tQuestion);
        		}
        	}
        }
        
        AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
        
        EventLog log = new EventLog();
    	log.setCreateTs(new Date());
    	log.setCreateUsername(sessionUser.getName());

    	log.setObjectClass(TransactionQuestion.class.getSimpleName());
    	log.setOperation(TransactionQuestion.findTransactionQuestion(id).getQuestion()+" Deleted");
    	log.setOperation(TransactionQuestion.findTransactionQuestion(id).getStateOrProvince().getCode()+" - "+TransactionQuestion.findTransactionQuestion(id).getQuestion()+" Deleted");
    	log.persist();
    	
        
        TransactionQuestion.findTransactionQuestion(id).remove();
        
        for(TransactionQuestion tq : deleteList)
        {
        	LOGGER.error("About to Delete Trial Group Transaction Question:  "+tq.getId()+"  :  "+tq.getQuestion());
        	tq.deleteTransactionQuestionByTrialGroup(tq);
        }
        
 
        return "redirect:/transactionquestion/list";         
     
    }
	
	@RequestMapping(value = "/transactionquestion/create/single", method = RequestMethod.POST)    
    public String processCreateSingle(@RequestParam(value = "stateOrProvince", required = false) Long stateId,
    		@RequestParam(value = "type", required = false) String type,
    		@RequestParam(value = "question", required = false) String question,
    		HttpSession session, 
    		ModelMap modelMap) {    
		
		TransactionQuestion tq = new TransactionQuestion();
		
	    if(TransactionQuestion.findTransactionQuestionByQuestionAndState(question, StateOrProvince.findStateOrProvince(stateId)) == null)
	    {
		
	    	tq.setStateOrProvince(StateOrProvince.findStateOrProvince(stateId));
	    	tq.setType(type);
	    	tq.setQuestion(question);
		
	    	AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
	    	tq.setCreateUsername(sessionUser.getName());
	    	tq.setUpdateUsername(sessionUser.getName());
	    	tq.setCreateTs(new Date());
			tq.setUpdateTs(new Date());
		
			tq.persist();
		
			EventLog log = new EventLog();
			log.setCreateTs(new Date());
			log.setCreateUsername(sessionUser.getName());

			log.setObjectClass(TransactionQuestion.class.getSimpleName());
			log.setOperation(StateOrProvince.findStateOrProvince(stateId).getCode()+" - "+question+" Created");
			log.persist();
	    }
	    else
	    {
	    	tq = TransactionQuestion.findTransactionQuestionByQuestionAndState(question, StateOrProvince.findStateOrProvince(stateId));
	    }
		
		
		return "redirect:/transactionquestion/" + tq.getId();         
    }
	
	@RequestMapping(value = "/transactionquestion/create/multiple", method = RequestMethod.POST)    
    public String processCreateMultiple(@RequestParam(value = "stateOrProvince", required = false) Long stateId,
    		@RequestParam(value = "type", required = false) String type,
    		@RequestParam(value = "questions", required = false) String questions,
    		HttpSession session,
    		ModelMap modelMap) {    

		
		String[] arr = questions.split(",");
		
		for(String question : arr)
		{
			TransactionQuestion tg = new TransactionQuestion();

			if(TransactionQuestion.findTransactionQuestionByQuestionAndState(question, StateOrProvince.findStateOrProvince(stateId)) == null)
			{
				
			
				tg.setStateOrProvince(StateOrProvince.findStateOrProvince(stateId));
				tg.setType(type);
				tg.setQuestion(question);
			
				AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
				tg.setCreateUsername(sessionUser.getName());
				tg.setUpdateUsername(sessionUser.getName());
				tg.setCreateTs(new Date());
				tg.setUpdateTs(new Date());
			
				EventLog log = new EventLog();
				log.setCreateTs(new Date());
				log.setCreateUsername(sessionUser.getName());

				log.setObjectClass(TransactionQuestion.class.getSimpleName());
				log.setOperation(StateOrProvince.findStateOrProvince(stateId).getCode()+" - "+question+" Created");
				log.persist();
			
			
				tg.persist();
				
			}
			
			
		}
		
		return "redirect:/transactionquestion/list";           
    }
	
}
